package mwa.cs.hh.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.ArDAO;
import mwa.cs.dao.RequestDAO;
import mwa.cs.database.Database;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS36004Srvl
 */
public class CS36004Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private int vnSiteId;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS36004Srvl() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    @SuppressWarnings({ "unchecked", "unused" })
	public void processRequest(HttpServletRequest request,
	HttpServletResponse response) throws ServletException, IOException {
    	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
    	request.setCharacterEncoding("UTF-8");
   		response.setCharacterEncoding("UTF-8");
   		response.setContentType("text/JSON");
   		String vaProcessType = request.getParameter("methodType");
		if (vaProcessType.equals("getDataTable")){
			getDataTable(request, response);
		}
	}

    @SuppressWarnings({ "unchecked", "unused" })
    public void getDataTable(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Database db = new Database();
		JSONObject voObject = new JSONObject();
		PrintWriter voOut = response.getWriter();	
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		DecimalFormat voFormatter = new DecimalFormat("#,###.00");
		String vaAccount = "";
		String vaStartDate = "";
		String vaToDate = "";
		String vaShowDate = "";
		String vaMeterSerialNumber = "";
		if(request.getParameter("sSearch_1") != null){
			if (request.getParameter("sSearch_0").equals("1")) {
				if (request.getParameter("sSearch_1").equals("")) {
					vaAccount = "";
				} else {
					vaAccount = request.getParameter("sSearch_1").trim();
				}
			} else {
				vaAccount = "-1";
			}
			if (request.getParameter("sSearch_2").equals("")) {
				vaStartDate = "";
			} else {
				vaStartDate = JDate.saveDate(request.getParameter("sSearch_2").trim());
			}
			if (request.getParameter("sSearch_3").equals("")) {
				vaToDate = "";
			} else {
				vaToDate = JDate.saveDate(request.getParameter("sSearch_3").trim());
			}
		}
		
		String[] vaColumnsASC = { "ar.current_read_date ASC", "cm.meter_serial_number ASC", "ar.current_read_number ASC",
				"ar.current_read_date ASC", "ar.consumption ASC", "ar.water_charge ASC", "ar.water_fee ASC",
				"ar.vat_amount ASC", "ar.total_amount ASC"};
		String[] vaColumnsDESC = { "ar.current_read_date DESC", "cm.meter_serial_number DESC", "ar.current_read_number DESC",
				"ar.current_read_date DESC", "ar.consumption DESC", "ar.water_charge DESC", "ar.water_fee DESC",
				"ar.vat_amount DESC", "ar.total_amount DESC"};

		String paSortColumn = null;
		int pnStart = Integer.parseInt(request.getParameter("iDisplayStart")); // 0
		int vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
		int vnSortColumn = Integer.parseInt(request.getParameter("iSortCol_0")); // 0, 1, 2, 3
		String vaSortDirection = request.getParameter("sSortDir_0");

		if (vaSortDirection.equals("asc")) {
			paSortColumn = vaColumnsASC[vnSortColumn];
		}
		if (vaSortDirection.equals("desc")) {
			paSortColumn = vaColumnsDESC[vnSortColumn];
		}
		
		ArDAO voArDAO = new ArDAO(db);
		List<Map<String , Object>> voListFindAll = null;
		Map<String , Object> voMapItem = null;
		int pnEnd = pnStart + vnAmount;
		int vnTotalRecords = voArDAO.getCountAllArByAccount(vnSiteId, vaAccount, vaStartDate, vaToDate);
		int vnTotalDisplayRecords = 0;
		if (vnAmount == -1) {
			voListFindAll = voArDAO.findAllArByAccount(vnSiteId, vaAccount, vaStartDate, vaToDate, paSortColumn);
			vnTotalDisplayRecords = vnTotalRecords;
		} else {
			voListFindAll = voArDAO.findArByAccount(vnSiteId, vaAccount, vaStartDate, vaToDate, paSortColumn, pnStart, pnEnd);
			vnTotalDisplayRecords = voArDAO.getCountAllArByAccount(vnSiteId, vaAccount, vaStartDate, vaToDate);
		}
		for(int i = 0; i < voListFindAll.size() ; i++){
			voMapItem = voListFindAll.get(i);
			voColumn = new JSONArray();
			voColumn.add(i + 1);
			vaMeterSerialNumber = "" + voMapItem.get("METER_SERIAL_NUMBER");
			voColumn.add(vaMeterSerialNumber.equals("null") ? "-" : voMapItem.get("METER_SERIAL_NUMBER"));
			voColumn.add(Integer.parseInt("" + voMapItem.get("CURRENT_READ_NUMBER")) == 0 ? "-" : voMapItem.get("CURRENT_READ_NUMBER"));
			vaShowDate = "" + voMapItem.get("CURRENT_READ_DATE");
			voColumn.add(vaShowDate.equals("null") ? "-" : JDate.showDate(vaShowDate));
			voColumn.add(Double.parseDouble("" + voMapItem.get("CONSUMPTION")) == 0 ? "0" : voMapItem.get("CONSUMPTION"));
			voColumn.add(Double.parseDouble("" + voMapItem.get("WATER_CHARGE")) == 0 ? "0.00" : voFormatter.format(voMapItem.get("WATER_CHARGE")));
			voColumn.add(Double.parseDouble("" + voMapItem.get("WATER_FEE")) == 0 ? "0.00" : voFormatter.format(voMapItem.get("WATER_FEE")));
			voColumn.add(Double.parseDouble("" + voMapItem.get("VAT_AMOUNT")) == 0 ? "0.00" : voFormatter.format(voMapItem.get("VAT_AMOUNT")));
			voColumn.add(Double.parseDouble("" + voMapItem.get("TOTAL_AMOUNT")) == 0 ? "0.00" : voFormatter.format(voMapItem.get("TOTAL_AMOUNT")));
			voRow.add(voColumn);
		}
		
		voObject.put("iTotalRecords", voListFindAll.size());
		voObject.put("iTotalDisplayRecords", voListFindAll.size());
		voObject.put("aaData", voRow);
		//db.close();
		voOut.print(voObject.toJSONString());
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
